<?php
/**
 * @todo set callbacks for different entities inside the table
 */
class DAOTable {
	protected $src;
	protected $data;
	protected $rowCallbacks=array();

	public function __construct(CDbCommand $src=NULL) {
		$this->src = $src;
	}
	public function setSource(CDbCommand $src) {
		$this->src = $src;
	}
	public function getSource(CDbCommand $src) {
		return $this->src;
	}
	public function __toString() {
		$headers = $this->getHeaders();
		if(!count($headers)) {
			return NULL;
		}
		$r = '<table class="dao-table" width="100%">';
		$t = "\n<tr>";
		foreach($headers as $colname) {
			$t .= "<th>$colname</th>";
		}
		$r .= $t . "</tr>";
		$t = '';
		foreach($this->data as $row) {
			$t .= "\n<tr>";
			foreach($row as $colname => $val) {
				$t .= '<td>'.$this->wrap($colname,$val).'</td>';
			}
			$t .= "</tr>";
		}
		return $r."\n$t</table>";
	}
	public function setWrap($colname,$callback) {
		$this->rowCallbacks[$colname] = $callback;
	}
	public function wrap($name,$value) {
		if(!array_key_exists($name,$this->rowCallbacks)) {
			return $value;
		}
		return call_user_func($this->rowCallbacks[$name],$name,$value);
	}
	public function getHeaders() {
		if(!$this->data) {
			$this->query();
		}
		$stmt = $this->src->getPdoStatement();
		$cols = $stmt->columnCount();
		$r = array();
		for($i=0;$i<$cols;$i++) {
			$col = $stmt->getColumnMeta($i);
			$r[] = $col['name'];
		}
		return $r;
	}
	public function query() {
		return $this->data = $this->src->query();
	}
}
